<?php
/**
 * Created by PhpStorm.
 * Date: 2021/1/25
 * Time: 12:51 PM
 */
namespace app\admin\controller;

use app\admin\model\Images;
use think\facade\View;

class Attachment extends Base
{
    // 资源列表
    public function index()
    {
        if (request()->isAjax()) {

            $limit = input('param.limit');
            $imgName = input('param.name');

            $where = [];
            if (!empty($imgName)) {
                $where[] = ['name', 'like', $imgName . '%'];
            }

            $imagesModel = new Images();
            $list = $imagesModel->getImagesList($limit, $where);

            if(0 == $list['code']) {

                return json(['code' => 0, 'msg' => 'ok', 'count' => $list['data']->total(), 'data' => $list['data']->all()]);
            }

            return json(['code' => 0, 'msg' => 'ok', 'count' => 0, 'data' => []]);
        }

        // TODO 图片的限制内容
        View::assign([
            'img' => config('images'),
            'fileLimit' => ini_get("upload_max_filesize")
        ]);

        return View::fetch();
    }

    // 上传图片
    public function upload()
    {
        $file = request()->file('file');
        // 上传到本地服务器
        try {

            $imageConf = config('images');
            $extMap = explode('|', $imageConf['ext']);
            $mineMap = explode(',', $imageConf['acceptMime']);

            // 检测文件类型
            $mine = $file->getMime();
            if (!in_array($mine, $mineMap)) {
                return json(['code' => -2, 'data' => [], 'msg' => '上传图片类型有误']);
            }

            // 检测文件后缀
            $ext = $file->getOriginalExtension();
            if (!in_array($ext, $extMap)) {
                return json(['code' => -3, 'data' => [], 'msg' => '上传图片类型有误']);
            }

            $imageModel = new Images();
            $has = $imageModel->checkImageExist($file->hash());
            if ($has['code'] != 0) {
                return json($has);
            }

            // 存到本地
            $saveName = \think\facade\Filesystem::disk('public')->putFile('comimg', $file);

            // 存储入库
            $sourceId = (new Images())->addImages([
                'name' => $file->getOriginalName(),
                'sha1' => $file->hash(),
                'url' => '/storage/' . $saveName,
                'path' => app()->getRootPath() . 'public/storage/' . $saveName,
                'folder' => 'comimg/' . date('Ymd'),
                'type' => 'local',
                'create_time' => date('Y-m-d H:i:s')
            ]);

            // TODO 触发上传后事件 后期增加第三方存储
            event('add_upload_after', [
                'file' => $file,
                'name' => $saveName,
                'sourceId' => $sourceId
            ]);
        } catch (\think\exception\ValidateException $e) {

            return json(['code' => -1, 'data' => [], 'msg' => $e->getMessage()]);
        }

        return json(['code' => 0, 'data' => ['url' => '/storage/' . $saveName], 'msg' => '上传成功']);
    }

    // 删除图片
    public function del()
    {
        if (request()->isAjax()) {

            $sourceId = input('param.id');
            $path = input('param.path');

            $imageModel = new Images();
            $res = $imageModel->deleteImg($sourceId);

            @unlink($path);

            // TODO 触发删除后事件 后期增加第三方存储
            event('delete_upload_after', [
                'id' => $sourceId,
                'path' => $path
            ]);

            return json($res);
        }
    }

    // 展示图片资源
    // TODO 此处仅考虑本地文件，后期扩展成oss等第三方
    public function show()
    {
        // 点击不同目录显示
        if (request()->isAjax()) {

            $path = input('param.path');
            $imagesData = glob($path . '/*');
            $list = [];
            if (!empty($imagesData)) {

                foreach ($imagesData as $file) {
                    $imgMap = glob($file . '/*');
                    if (empty($imgMap)) {
                        $list[] = [
                            'url' => '/' . $file
                        ];
                    } else {
                        foreach ($imgMap as $file2) {
                            $list[] = [
                                'url' => '/' . $file2
                            ];
                        }
                    }
                }
            }

            return json(['code' => 0, 'data' => $list, 'msg' => 'success']);
        }

        $num = input('param.num');
        $imagesData = glob('storage/*');
        $children = [];
        $i = 1;
        foreach ($imagesData as $key => $vo) {
            $fileMap = glob($vo . '/*');
            $i++;
            $children[$key] = [
                'title' => explode('/', $vo)['1'],
                'id' => $i,
                'parentId' => 1,
                'spread' => true
            ];

            $pid = $i;
            if (!empty($fileMap)) {
                foreach ($fileMap as $k => $v) {
                    $i++;
                    $children[$key]['children'][] = [
                        'title' => explode('/', $v)['2'],
                        'id' => $i,
                        'parentId' => $pid
                    ];
                }
            }
        }

        $tree = [
            'title' => 'storage',
            'id' => 1,
            'spread' => true,
            'children' => $children
        ];

        View::assign([
            'num' => $num,
            'tree' => json_encode($tree)
        ]);

        return View::fetch();
    }
}